# yaml_update.py
from ruamel.yaml import YAML
import os

# 直接在方法中改yaml文件不适合大型协作项目，谨慎使用
class YamlUpdater:
    def __init__(self, file):
        self.file = file
        self.yaml = YAML()
        self.yaml.indent(mapping=2, sequence=4, offset=2)
        self.yaml.default_flow_style = False

    def update(self, section, key, value):
        # 读取（保留格式和注释）
        with open(self.file, 'r', encoding='utf-8') as f:
            data = self.yaml.load(f)

        # 修改值
        if section in data:
            data[section][key] = value
        else:
            data[section] = {key: value}

        # 写回（保留格式）
        with open(self.file, 'w', encoding='utf-8') as f:
            self.yaml.dump(data, f)

        print(f"✅ 已更新 {section}.{key} = {value}")